package com.example.myprojectoffeixue;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.localization.Gateway;
import com.localization.GatewayRequestUtil;
import com.localization.SendUtil;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

public class KtGroupActivity extends Activity {
    MyApplication m;
    public String KT_temperature;
    public String Current_temperature;

    public String powerStatus;
    private SheBeiClass sb;
    KtGroupAdapter kt;
    public HashMap<String, Extra> kt3_map;
    String Key;
    TextView set_finish;
    int i;
    ArrayList<String> flag;
    private ListView actualListView;
    private ArrayList<String> kt_list = new ArrayList<>();
    private HashMap<String, String> kt2_map = new HashMap<>();

    Handler hand = new Handler() {

        public void handleMessage(android.os.Message msg) {

            if (msg.what == 32) {
                kt3_map = m.kt_map;
                kt.notifyDataSetChanged();
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kt_group);
    }
    public void info() {
        PullToRefreshListView kt_group = (PullToRefreshListView) findViewById(R.id.kt_group);
        kt_group.setMode(PullToRefreshBase.Mode.DISABLED);
        actualListView = kt_group.getRefreshableView();
        //actualListView= (ListView) findViewById(R.id.kt_group);
        m = (MyApplication) getApplication();
        sb = new SheBeiClass();
        if (flag == null) {
            flag = new ArrayList<String>();
        } else {
            flag.clear();
            kt_list.clear();
            kt2_map.clear();
            kt3_map.clear();
            set_finish.setText("一键设置");
        }

        m.t=new Extra();
        m.t.powerStatus="00";
        m.t.mode="01";
        m.t.speed="00";
        m.t.temperature="16";
        m.t.roomTemperature="25";
        m.t.timerStatus="00";
        m.t.timerHour="00";
        m.t.timerMin="00";
        m.t.timerType="01";

        for(int i=0;i<m.lsb7.size();i++){
            String ieee=m.lsb7.get(i).ieee;
            String port=m.lsb7.get(i).port;
            String Key = ieee + port;
            m.kt_map.put(Key, m.t);
        }

        if (m.lsb7.size() != 0) {
            for (i = 0; i < m.lsb7.size(); i++) {
                flag.add("0");
                sb.mac = m.lsb7.get(i).mac;
                sb.ieee = m.lsb7.get(i).ieee;
                sb.port = m.lsb7.get(i).port;
                sb.cmd = "1011";
                sb.status = "06";
                String t = JSON.toJSONString(sb);
                if (!Gateway.MacSocke.containsKey(sb.mac)) {
                    if(m.flag3){
                    m.c.send(t);}
                }else{
                    Log.d("内网发送","内网发送");
                    String cmd= GatewayRequestUtil.createCentraAirSearchStr(sb.ieee,sb.port);
                    SendUtil.Mac = sb.mac;
                    SendUtil.cmd = cmd;
                    SendUtil.hand.sendEmptyMessage(0);
                }
                Key = sb.ieee + sb.port;
                kt_list.add(Key);
                String name = m.lsb7.get(i).deviceName;
                if (name!=null) {
                    kt2_map.put(Key, name);
                } else {
                    name = "中央空调";
                    kt2_map.put(Key, name);

                }

            }
        }




        kt_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ("一键设置".equals(set_finish.getText().toString())) {
                    Intent it = new Intent(KtGroupActivity.this, KongTiaoActivity.class);
                    it.putExtra("ieee", m.lsb7.get(position - 1).ieee);
                    it.putExtra("port", m.lsb7.get(position - 1).port);
                    it.putExtra("mac", m.lsb7.get(position - 1).mac);
                    startActivity(it);
                }

            }
        });
        kt3_map = m.kt_map;
        kt = new KtGroupAdapter(kt_list, KtGroupActivity.this, kt2_map, kt3_map, flag);
        actualListView.setAdapter(kt);
        actualListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            private EditText et;
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final String ieee = m.lsb7.get(position-1).ieee;
                final String port = m.lsb7.get(position-1).port;
                final String h = m.lsb7.get(position-1).deviceId;
                final String mac = m.lsb7.get(position-1).mac;
               TextView  tv = (TextView) view.findViewById(R.id.name_item);
                AlertDialog.Builder builder = new AlertDialog.Builder(KtGroupActivity.this);
                builder.setTitle("重命名");
                builder.setIcon(android.R.drawable.ic_dialog_info);
                et = new EditText(KtGroupActivity.this);
                et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
                et.setHint("请输入新的设备名字");
                builder.setView(et);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final String  name = et.getText().toString();
                        Kuaiguanutil k = new Kuaiguanutil();
                        k.ieee = ieee;
                        k.port = port;
                        k.deviceId = h;
                        k.deviceName = name;
                        k.mac = mac;
                        String l2 = JSON.toJSONString(k);
                        l2 = AESUtil.encrypt(l2);
                        HttpUtils httpUtils = new HttpUtils();
                        RequestParams params = new RequestParams();
                        params.setHeader("Content-Type", "application/json");
                        try {
                            params.setBodyEntity(new StringEntity(l2, "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.renameDevice, params,
                                new RequestCallBack<String>() {

                                    @Override
                                    public void onFailure(HttpException arg0, String arg1) {
                                        HttpConnection.toastLog("网络异常", KtGroupActivity.this);
                                    }

                                    @Override
                                    public void onSuccess(ResponseInfo<String> arg0) {
                                        if (arg0.result != null && !("".equals(arg0.result))) {
                                            arg0.result = AESUtil.decrypt(arg0.result);
                                            GateWay Gw2 = JSON.parseObject(arg0.result, GateWay.class);
                                            if (0 == Gw2.status) {
                                                m.lsb7.get(position-1).deviceName = name;
                                                kt_list.clear();
                                                kt2_map.clear();
                                                if (m.lsb7.size() != 0) {
                                                    for (i = 0; i < m.lsb7.size(); i++) {
                                                        flag.add("0");
                                                        sb.mac = m.lsb7.get(i).mac;
                                                        sb.ieee = m.lsb7.get(i).ieee;
                                                        sb.port = m.lsb7.get(i).port;
                                                        sb.cmd = "1011";
                                                        sb.status = "06";
                                                        String t = JSON.toJSONString(sb);
                                                        if (!Gateway.MacSocke.containsKey(sb.mac)) {
                                                            if(m.flag3){
                                                            m.c.send(t);}
                                                        }else{
                                                            String cmd= GatewayRequestUtil.createCentraAirSearchStr(sb.ieee,sb.port);
                                                            SendUtil.Mac = sb.mac;
                                                            SendUtil.cmd = cmd;
                                                            SendUtil.hand.sendEmptyMessage(0);
                                                        }
                                                        Key = sb.ieee + sb.port;
                                                        kt_list.add(Key);
                                                        String name = m.lsb7.get(i).deviceName;
                                                        if (name!=null) {
                                                            kt2_map.put(Key, name);
                                                        } else {
                                                            name = "中央空调";
                                                            kt2_map.put(Key, name);
                                                        }
                                                    }
                                                }
                                                kt.notifyDataSetChanged();



                                            } else {
                                                HttpConnection.toastLog("修改失败", KtGroupActivity.this);
                                            }

                                        } else {
                                            HttpConnection.toastLog("服务器错误", KtGroupActivity.this);

                                        }
                                    }

                                });


                    }
                });
                builder.setNegativeButton("取消", null);
                AlertDialog dialog = builder.create();
                dialog.show();


                return true;
            }
        });




        LinearLayout tfinish = (LinearLayout) findViewById(R.id.iv_mykaiguan);
        tfinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        set_finish = (TextView) findViewById(R.id.wancheng);

        set_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("完成".equals(set_finish.getText().toString())) {
                    boolean flag3=true;
                    for(int i=0;i<flag.size();i++){
                        if("1".equals(flag.get(i))){
                            flag3=false;
                        }
                    }
                    if (!flag3) {
                        ArrayList<String> power =new ArrayList<String>();

                        for(int i=0;i<m.lsb7.size();i++){
                            if("1".equals(flag.get(i))){
                                String key=m.lsb7.get(i).ieee+m.lsb7.get(i).port;
                                power.add(kt3_map.get(key).powerStatus);
                            }
                        }
                               int x=0;
                               int y=0;

                        for(int i=0;i<power.size();i++){

                            if("00".equals(power.get(i))){
                                x=1;
                            }else if("01".equals(power.get(i))){
                            y=1;
                            }
                        }

                         if(x==1&&y==1){
                             HttpConnection.showToast(getBaseContext(),"请选择开关状态一致的空调");
                         }else {
                             Intent it = new Intent(KtGroupActivity.this, KongTiaoActivity.class);
                             it.putStringArrayListExtra("extra", flag);
                             it.putExtra("flag", "flag");
                             startActivity(it);
                         }
                    } else {
                        HttpConnection.showToast(getBaseContext(),"请选择要操纵的空调");
                    }
                }
                set_finish.setText("完成");
                kt.flag = true;
                kt.notifyDataSetChanged();

            }
        });


    }

    @Override
    protected void onStart() {
        info();
        m.hand = hand;
        kt3_map = m.kt_map;
        kt.notifyDataSetChanged();

        super.onStart();
    }


}
